package com.lxhdj.common.handle;

import com.lxhdj.common.vo.ResultResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 数据转换异常
     * @param e
     * @param httpServletResponse
     * @throws IOException
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public void httpMessageNotReadableExceptionHandle(HttpMessageNotReadableException e, HttpServletResponse httpServletResponse) throws IOException {
//        Response restResponse = Response.fail("数据转换异常，请检查请求数据是否存在格式错误");
        log.error("数据转换异常，请检查请求数据是否存在格式错误: ", e);

        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write("数据转换异常:"+e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultResponse exceptionHandle(Exception e) throws IOException {
        log.error("Exception：", e);
        return ResultResponse.fail(500, e.getMessage());
    }

    @ExceptionHandler(Error.class)
    @ResponseBody
    public ResultResponse exceptionHandle(Error e) throws IOException {
        log.error("Error： ", e);
        return ResultResponse.fail(500, e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResultResponse exceptionHandle(Throwable e) throws IOException {
        log.error("Throwable： ", e);
        return ResultResponse.fail(500, e.getMessage());
    }


}
